let {creatUser,updateUser}=require('../server/user.js')
let jwt=require('jsonwebtoken')
let { JWT_SECRET}=require('../config/config.default.js')
let {getUser}=require('../server/user.js')
class user{
    async register(ctx,next){
       let {name,password}=ctx.request.body
       try{
        let res=await creatUser({name,password})
        ctx.body={
            code:200,
            message:"用户注册成功",
            result:{
                id:res.id,
                name:res.name
            }
        }
       }catch(err){
           console.error('创建用户出错'+err)
           ctx.app.emit('emit',{
              code:'50000',
              message:"创建用户出错",
              result:""
           },ctx)
       }
       
    }

    async login(ctx,next){
        let {name}=ctx.request.body
       try{
           let {password,...res}=await getUser({name})
           ctx.body={
               code:200,
               message:'登入成功',
               result:{
                   res,
                   token:jwt.sign(res,JWT_SECRET,{expiresIn:'2d'})
               }
           }
       }catch(err){
           console.error('用户登入失败'+err)
       }
    }

    async changePwd(ctx,next){
      let {name,password}=ctx.request.body

      try{
        let res=await updateUser({name,password})
        if(res){
            ctx.body={
                code:200,
                message:"密码更新成功",
                result:''
            }
            return
        }else{
            ctx.app.emit('error',{
                code:'40000',
                message:"密码更新失败",
                result:''
            },ctx)
        }
      }catch(err){
          console.error('修改密码失败')
      }
    }
}

module.exports=new user()